package mysrpringboot.springboot.redisConfig;

import com.github.jedis.lock.JedisLock;
import mysrpringboot.springboot.Dao.OrderDao;
import mysrpringboot.springboot.Service.SellService;
import mysrpringboot.springboot.rocketmq.Myconsumer;
import mysrpringboot.springboot.rocketmq.Myproduce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;

@Component
public class RedisLock {

    @Autowired
    private SellService sellService;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private Myproduce myproduce;

    public static Integer num=null;

          public void lock(){
              String redisKey="lock";
              num=sellService.findNum();
              Jedis jedis = new Jedis("127.0.0.1",6379);
              try{
                  jedis.set(redisKey,"0");

                  jedis.close();
              }catch (Exception e){
                  e.printStackTrace();
              }

              Jedis jedis1 = new Jedis("127.0.0.1",6379);
               try{
                   jedis1.watch(redisKey);
                   String redisValue = jedis1.get(redisKey);
                   int valInteger=Integer.valueOf(redisValue);
                   String orderId = UUID.randomUUID().toString();

                   if(valInteger<num){
                      Transaction tx=jedis1.multi();
                      tx.incr(redisKey);
                      List list =tx.exec();
                      if(list!=null&&list.size()>0){
                          myproduce.produce(orderId);
                      }else{
                               System.out.println("秒杀失败");
                      }
                   }
                   else{
                               System.out.println("卖完了");
                   }
               }
               catch (Exception e){
                     e.printStackTrace();
               }finally {
                   jedis1.close();
               }
          }

}
